<template>
  <form-modal
    width="600px"
    :title="title + 'Form'"
    v-model="modalVisible"
    @cancel="handleClose"
  >
    <a-form-model
      ref="formRef"
      :model="formData"
      :rules="formRule"
      v-bind="layoutConfig.formLayout"
    >
      `%formCode%`
    </a-form-model>
    <template #footer v-if="!isPreview">
      <a-button @click="handleClose"> 取消 </a-button>
      <a-button
        type="primary"
        style="margin-left: 25px"
        :loading="submitLoading"
        @click="handleOk"
      >
        提交
      </a-button>
    </template>
  </form-modal>
</template>

<script lang="ts">
import {
  Component,
  Vue,
  Prop,
  ModelSync,
  Ref,
  Watch,
} from "vue-property-decorator";

const defaultFormData: any = `%formDataCode%`;

@Component
export default class FormInfo extends Vue {
  @ModelSync("value", "input", { type: Boolean, default: false })
  modalVisible!: boolean;

  @Prop({ type: String, default: "add" }) mode!: string;

  @Prop({ type: Object, default: () => ({}) }) recordInfo!: any;

  layoutConfig: any = `%layoutConfigCode%`;

  submitLoading: boolean = false;

  get isPreview() {
    return this.mode === "preview";
  }

  get title() {
    return this.isPreview ? "查看" : this.mode === "edit" ? "编辑" : "新增";
  }

  @Watch("value")
  handleValueChange(nval: boolean) {
    if (nval) {
      this.formData = {
        ...this.recordInfo,
      };
    } else {
      this.formData = { ...defaultFormData };
    }
  }

  formData: any = { ...defaultFormData };

  formRule = `%formRuleCode%`;

  @Ref("formRef")
  formRef: any;
  async handleOk() {
    try {
      await this.formRef.validate();
      this.submitLoading = true;
      const isEdit = !!this.formData.id;
      // const remoteMethod = isEdit ? editCharacter : addCharacter;
      // const [err] = await remoteMethod({
      //   ...this.formData,
      // });
      // this.submitLoading = false;
      // if (!err) {
      //   this.$message.success(`${isEdit ? "编辑" : "添加"}成功`);
      //   this.$emit("refresh");
      //   this.handleClose();
      // }
    } catch (e) {
      this.submitLoading = false;
      console.error("onSubmit error", e);
    }
  }

  handleClose() {
    this.modalVisible = false;
  }
}
</script>
